import os
import glob
import argparse
import unittest
from gmssl import *

def read_binary_file(file_path):
    """读取二进制文件内容并转换为字符串"""
    with open(file_path, 'rb') as f:
        binary_data = f.read()
        # 尝试解码为字符串，如果失败则用十六进制表示
        return binary_data.hex().upper()

def hash(msg_file, dgst_file):
    """读取二进制文件内容并转换为字符串"""
    with open(msg_file, 'rb') as f:
        msg_data = f.read()

    with open(dgst_file, 'rb') as f:
        dgst_data = f.read()

    sm3 = Sm3() 
    sm3.update(msg_data)
    dgst = sm3.digest()
    assert dgst == dgst_data, "杂凑值错误"

def main():
    parser = argparse.ArgumentParser(description='遍历目录中的二进制文件')
    parser.add_argument('directory', help='目标目录路径')
    args = parser.parse_args()
    directory = args.directory

    if not os.path.isdir(directory):
        print(f"错误：目录不存在 - {directory}")
        return

    # 创建输出内容
    merged_content = ""
    
    # 遍历0-9，合并对应的公钥和私钥文件
    for i in range(10):
        msg_file = os.path.join(directory, f'sm3_msg_{i}')
        hash_file = os.path.join(directory, f'hash_{i}')

        hash(msg_file, hash_file)

        # 读取文件内容
        msg_content = read_binary_file(msg_file)
        hash_content = read_binary_file(hash_file)

        
        length = int(len(msg_content) / 2)
        
        # 添加到合并内容
        merged_content += f"消息长度= {length:08x}\n"
        merged_content += f"消息=\n{msg_content}\n"
        merged_content += f"杂凑值=\n{hash_content}\n"
        merged_content += "\n"
        
    
    # 写入到txt文件
    output_file = 'sm3正确性.txt'
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(merged_content)
    
    print(f"合并完成，结果已保存到 {output_file}")

if __name__ == "__main__":
    main()
